package com.net.oil.action;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.net.oil.R;
import com.net.oil.action.bean.ActionDetailBean;
import com.net.oil.action.contract.ActionDetailContract;
import com.net.oil.action.presenter.ActionDetailPresenter;
import com.net.oil.app.Constant;
import com.net.oil.app.UserInfoManager;
import com.net.oil.base.BaseActivity;
import com.net.oil.car.MyCarDetailActivity;
import com.net.oil.coupon.CouponActivity;
import com.net.oil.http.AppHttpCode;
import com.net.oil.http.AppUrl;
import com.net.oil.http.custom.ApiException;
import com.net.oil.luckPan.LuckPanActivity;
import com.net.oil.user.LoginActivity;
import com.net.oil.user.MyReceiveGoodsActivity;
import com.net.oil.util.DateFormat;
import com.net.oil.util.DisplayUtil;
import com.net.oil.util.WebViewUtil;
import com.net.oil.util.glide.GlideUtil;
import com.net.oil.widget.ToastUtil;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 活动类型详情：
 * 1：直接领取优惠券
 * 2：直接领取产品
 * 6：大转盘抽奖活动
 * 5：公告活动
 */
public class ActionDetailActivity extends BaseActivity<ActionDetailPresenter> implements ActionDetailContract.View {

    private static final int ACTION_TYPE_LOTTERY = 6;       //活动类型6，抽奖
    private static final int ACTION_TYPE_NORMAL = 5;        //活动类型5，公告活动
    private static final int ACTION_TYPE_GET_COUPON = 1;        //领取优惠券
    private static final int ACTION_TYPE_GET_PRODUCT = 2;       //领取产品

    @BindView(R.id.toolbar_go_back)
    ImageView toolbarGoBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.web_view)
    WebView webView;
    @BindView(R.id.action_button)
    Button actionButton;
    @BindView(R.id.banner_layout)
    RelativeLayout bannerLayout;
    @BindView(R.id.action_tips_tv)
    TextView actionTipsTv;
    @BindView(R.id.action_time_tv)
    TextView actionTimeTv;
    @BindView(R.id.action_end_time_tv)
    TextView actionEndTimeTv;
    @BindView(R.id.action_img)
    ImageView actionImg;
    @BindView(R.id.tips_layout)
    LinearLayout tipsLayout;
    @BindView(R.id.action_time_layout)
    LinearLayout actionTimeLayout;
    @BindView(R.id.coupon_end_time_layout)
    LinearLayout couponEndTimeLayout;

    private Context context;

    private WebSettings webSetting;

    private int actionId = -1;

    private ActionDetailBean actionDetailBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_action_detail);
        ButterKnife.bind(this);
        context = this;
        presenter = new ActionDetailPresenter(this);
        initView();
        initData();
    }

    private void initData() {
        Intent intent = getIntent();
        actionId = intent.getIntExtra(Constant.INTENT_ACTION_KEY, -1);

        if (actionId != -1) {
            showProgressDialog();
            presenter.getActionDetail(actionId);
        }
    }

    private void initView() {

        webSetting = webView.getSettings();
        webSetting.setJavaScriptEnabled(true);
        webSetting.setUseWideViewPort(true);  //将图片调整到适合webview的大小
        webSetting.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        webSetting.setSupportZoom(true);

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        int screenWidth = DisplayUtil.getScreenWidth();
        params.width = screenWidth;
        params.height = (int) (screenWidth / 2.3);
        actionImg.setLayoutParams(params);

    }

    private void updateView() {

        if (actionDetailBean != null) {

            if (!TextUtils.isEmpty(actionDetailBean.getImage())) {
                GlideUtil.getInstance().loadImage(this, actionImg, AppUrl.getImageUrl(actionDetailBean.getImage()), R.drawable.banner_err);
            }

            if (!TextUtils.isEmpty(actionDetailBean.getTitle())) {
                toolbarTitle.setText(actionDetailBean.getTitle());
            }
            if (!TextUtils.isEmpty(actionDetailBean.getContent())) {
                webView.loadData(WebViewUtil.getHtmlData(actionDetailBean.getContent()), "text/html; charset=UTF-8", null);
            }

            /* 6是抽奖 活动*/
            if (actionDetailBean.getType() == ACTION_TYPE_LOTTERY) {
                actionButton.setText("前往抽奖");
            } else if (actionDetailBean.getType() == ACTION_TYPE_NORMAL) {        //活动5，隐藏button
                setViewGone();
            } else {
                if (actionDetailBean.getIsApplyed() == 1) {
                    actionButton.setText("您已参与过该活动");
                } else {
                    actionButton.setText("参加该活动");
                }
            }

            if (!TextUtils.isEmpty(actionDetailBean.getTips())) {
                actionTipsTv.setText(actionDetailBean.getTips());
            }

            String sData = DateFormat.formatDateTime(actionDetailBean.getSdate(), DateFormat.FormatFlag.YDM);
            String eData = DateFormat.formatDateTime(actionDetailBean.getEdate(), DateFormat.FormatFlag.YDM);

            actionTimeTv.setText(sData + "~" + eData);

            String endTime = DateFormat.formatDateTime(actionDetailBean.getEndTime(), DateFormat.FormatFlag.YDM);
            actionEndTimeTv.setText(endTime);
        }
    }

    @OnClick({R.id.toolbar_go_back, R.id.action_button})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.toolbar_go_back:
                finish();
                break;
            case R.id.action_button:
                if (UserInfoManager.getInstance().isLogin()) {
                    /* 6是抽奖活动 */
                    if (actionDetailBean.getType() == ACTION_TYPE_LOTTERY) {
                        Intent intent = new Intent(this, LuckPanActivity.class);
                        intent.putExtra(Constant.INTENT_ACTION_ID_KEY, actionId);
                        startActivity(intent);
                    } else {
                        if (actionDetailBean.getIsApplyed() == 1) {
                            ToastUtil.showShortToast(this, "您已参与该活动，不能重复参与！");
                        } else {
                            presenter.getCoupon(actionId);
                        }
                    }
                } else {
                    startActivity(new Intent(this, LoginActivity.class));
                }
                break;
        }
    }

    /**
     * 如果活动是5，公告活动，则只显示banner图和富文本
     */
    public void setViewGone() {
        actionButton.setVisibility(View.GONE);
        tipsLayout.setVisibility(View.GONE);
        actionTimeLayout.setVisibility(View.GONE);
        couponEndTimeLayout.setVisibility(View.GONE);
    }

    /**
     * 获取活动详情成功
     *
     * @param actionDetailBean 活动详情
     */
    @Override
    public void getActionDetailSuccess(ActionDetailBean actionDetailBean) {
        dismissProgressDialog();
        this.actionDetailBean = actionDetailBean;
        updateView();
    }

    /**
     * 获取活动详情失败
     */
    @Override
    public void getActionDetailFailed() {
        dismissProgressDialog();
    }

    @Override
    public void getCouponSuccess() {
        ToastUtil.showSuccessToast(this, "领取成功");
        if (actionDetailBean != null){
            if (actionDetailBean.getType() == ACTION_TYPE_GET_COUPON){
                startActivity(new Intent(this, CouponActivity.class));
            }else if (actionDetailBean.getType() == ACTION_TYPE_GET_PRODUCT){
                startActivity(new Intent(this, MyReceiveGoodsActivity.class));
            }
        }
    }

    @Override
    public void getCouponFailed(ApiException e) {
        if (e.getErrorCode() == AppHttpCode.NO_CAR_INFO || e.getErrorCode() == AppHttpCode.NO_CAR_NUMBER) {
            if (!TextUtils.isEmpty(e.getErrorMessage())) {
                showErrDialog(e.getErrorMessage());
            } else {
                String message = "";
                if (e.getErrorCode() == AppHttpCode.NO_CAR_INFO) {
                    message = "请先前往爱车管理,添加爱车信息并完善车牌号信息";
                } else if (e.getErrorCode() == AppHttpCode.NO_CAR_NUMBER) {
                    message = "请先完善用户爱车的车牌号";
                }
                showErrDialog(message);
            }
        }
    }

    /**
     * 根据接口返回的code，如果code 为703或者702，则跳转到爱车详情
     *
     * @param message 提示信息（从接口message中取）
     */
    private void showErrDialog(String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage(message);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startActivity(new Intent(context, MyCarDetailActivity.class));
            }
        });
        builder.show();
    }
}
